<template>
  <div class="login">
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.phone"
        name="phone"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请填写手机号' }, { validator: checkPhone, message: '请输入正确内容' }]"
      />
      <van-field
        v-model="form.password"
        type="password"
        name="password"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }, { pattern: /^[a-zA-Z0-9]{6,12}$/, message: '请输入正确内容' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" :loading="isLoading" >提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { NavBar, Form, Button, Field, Toast } from 'vant'
import { login } from '@/services/user'
export default {
  components: {
    VanNavBar: NavBar,
    VanForm: Form,
    VanButton: Button,
    VanField: Field
  },
  name: 'Login',
  data () {
    return {
      form: {
        phone: '18201288771',
        password: '111111'
      },
      isLoading: false
    }
  },
  methods: {
    checkPhone (value) {
      return /^1\d{10}$/.test(value)
    },
    async onSubmit (values) {
      this.isLoading = true
      const { data } = await login(this.form)
      if (data.state === 1) {
        Toast.success('登录成功')
        this.$store.commit('setUser', data.content)
        this.$router.push(this.$route.query.directe || '/')
      } else {
        Toast.fail('登录失败')
      }
      this.isLoading = false
    },
    onClickLeft () {
      this.$router.go(-1)
    }
  }
}
</script>

<style>

</style>
